package com.example.JPopupMenu;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

/**
 * @Author 郅占伟
 * @ClassName MyJPopupMenu
 * @Description TODO
 * @Date 2024年10月10日
 * @Version: 1.0
 */
public class MyJPopupMenu extends JFrame {
    private JPopupMenu popupMenu;
    public MyJPopupMenu() {
        // 创建一个JPopupMenu菜单
        popupMenu = new JPopupMenu();

        // 创建三个JMenuItem菜单项
        JMenuItem refreshItem = new JMenuItem("刷新");
        JMenuItem createItem = new JMenuItem("新建");
        JMenuItem exitItem = new JMenuItem("退出");

        // 为exitItem菜单项添加事件监听器
        exitItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });

        // 向JPopupMenu菜单添加菜单项
        popupMenu.add(refreshItem);
        popupMenu.add(createItem);
        popupMenu.addSeparator();
        popupMenu.add(exitItem);

        // 为JFrame窗口添加clicked鼠标事件监听器
        this.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                System.out.println("鼠标点击：" + e.getButton());
                if (e.getButton() == MouseEvent.BUTTON3){
                    System.out.println("右键菜单弹出");
                    System.out.println("鼠标位置：" + e.getX() + "," + e.getY());
                    popupMenu.show(e.getComponent(), e.getX(), e.getY());
                }
            }
        });

        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLocation(200, 200);
        this.setSize(1200, 800);
        this.setVisible(true);

    }
}
